import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, logout as logoutApi, getStatus } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref('')
  const isAuthenticated = ref(false)

  const loginAction = async (userInfo) => {
    try {
      const res = await loginApi(userInfo)
      if (res.success) {
        token.value = res.data.token
        username.value = res.data.username
        isAuthenticated.value = true
        localStorage.setItem('token', res.data.token)
        const expiresAt = new Date().getTime() + 30 * 60 * 1000
        localStorage.setItem('tokenExpiresAt', expiresAt.toString())
      }
      return res
    } catch (error) {
      resetToken()
      if (error.response?.data?.message) {
        error.message = error.response.data.message
      }
      throw error
    }
  }

  const logoutAction = async () => {
    try {
      await logoutApi()
    } finally {
      resetToken()
    }
  }

  const resetToken = () => {
    token.value = ''
    username.value = ''
    isAuthenticated.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('tokenExpiresAt')
  }

  const checkTokenExpiration = () => {
    const expiresAt = localStorage.getItem('tokenExpiresAt')
    if (expiresAt && new Date().getTime() > parseInt(expiresAt)) {
      resetToken()
      return false
    }
    return true
  }

  const checkStatus = async () => {
    if (!checkTokenExpiration()) {
      throw new Error('Token expired')
    }
    
    try {
      const res = await getStatus()
      if (res.success) {
        isAuthenticated.value = res.data.isAuthenticated
        username.value = res.data.username
      }
      return res
    } catch (error) {
      resetToken()
      throw error
    }
  }

  return {
    token,
    username,
    isAuthenticated,
    login: loginAction,
    logout: logoutAction,
    resetToken,
    checkStatus,
    checkTokenExpiration
  }
}) 